package service

import (
	"encoding/json"
	Mysql "gin/database"
	"gin/model"
	"gin/validate"
	"github.com/Gre-Z/common/jtime"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"os"
	"strings"
	"time"
)

// 验证文件md5是否存在
func CheckFileMd5(MD5 string) (check bool, mediaData model.Media) {
	var mediaModel model.Media
	var err error

	mediaData, err = mediaModel.GetMediaDataByMD5(MD5)
	if err != nil {
		check = false
	} else {
		check = true
	}

	return
}

// 保存媒体数据
func CreateMedia(Data validate.AddMedia) (err error) {
	var mediaModel model.Media
	mediaModel.Md5Name = Data.Md5Name
	mediaModel.Md5 = Data.Md5
	mediaModel.Type = Data.Type
	mediaModel.Status = Data.Status
	mediaModel.Param = Data.Param
	mediaModel.Created = jtime.TstampTime(time.Now().Unix())

	// 填充UUID
	mediaModel.Uuid = uuid.NewV4().String()

	_, err = mediaModel.Insert()

	return
}

// 更新文件状态通过 Md5Name
func UpdateStatusByMd5Name(Md5Name string, Status string) (err error) {
	var mediaModel model.Media
	err = mediaModel.UpdateStatusByMd5Name(Md5Name, Status)
	return
}

// 通过Md5 Name 查找媒体
func SelectMediaByMd5Name(Md5Name string) (mediaData []model.Media, err error) {
	var mediaModel model.Media
	mediaData, err = mediaModel.SelectMediaByMd5Name(strings.Split(Md5Name, ","))
	return
}

// 通过Md5 Name 查找半天过去了还没有被删除的数据
func FindHalfDayMediaByMd5Name(Md5Name string) (mediaData model.Media, err error) {
	var mediaModel model.Media
	mediaData, err = mediaModel.FindHalfDayMediaByMd5Name(Md5Name)
	return
}

// 通过Md5 Name 查找半天过去了还没有被删除的数据
func UpdateHalfDayMediaCreatedByMd5Name(Md5Name string) (err error) {
	var mediaModel model.Media
	err = mediaModel.UpdateHalfDayMediaCreatedByMd5Name(Md5Name)
	return
}

// 更新文件状态通过 Md5Name
func RemoveMediaByMd5Name(Md5Name string) (err error) {
	var mediaModel model.Media

	// 1.先查找当前存在的文件
	mediaData, err := mediaModel.SelectMediaByMd5Name(strings.Split(Md5Name, ","))

	if err != nil {
		return
	}

	// 删除存在数据的文件夹
	basePath := viper.GetString("server.staticPath")
	for _, mediaItem := range mediaData {
		err = os.RemoveAll(basePath + mediaItem.Md5Name)
		if err != nil {
			break
		}
	}

	if err != nil {
		return
	}

	// 清除数据库数据
	err = mediaModel.RemoveMediaByMd5Name(strings.Split(Md5Name, ","))
	return
}

// 更新文件ext通过 Md5Name
func UpdateParamByMd5Name(Md5Name string, Ext string) (media model.Media, err error) {
	var mediaModel model.Media
	mediaData, err := mediaModel.GetMediaDataByMD5Name(Md5Name)
	if err != nil {
		return
	}
	var mediaParamData validate.MediaMetadata
	_ = json.Unmarshal(mediaData.Param, &mediaParamData)
	mediaParamData.Ext = Ext
	str, _ := json.Marshal(mediaParamData)
	dr := Mysql.DB.Model(&mediaModel).Where("id = ?", mediaData.Id).Update("param", str)
	if dr.Error != nil {
		err = dr.Error
		return
	}
	media, _ = mediaModel.GetMediaDataByMD5Name(Md5Name)
	return media, err
}
